﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using YYNY.Tools;
using YYNY.Tools.Dao;
using System.IO;
using Newtonsoft.Json.Linq;

namespace YYNY.Controllers
{
    public class UserController : Controller
    {
        BaseDao dao = new BaseDao();
        // GET: User
        public ActionResult Index()
        {
            return View();
        }

        public ActionResult UserView()
        {
            string UserId = Request.Cookies["UserID"].Value;
            string sql = "";
            sql = "select * from o_Authority where UserId=" + UserId;
            var AuthList = dao.GetList(sql, new string[] { "Type", "Name", "UserId" });
            ViewBag.AuthList = AuthList;
            return View("UserView");

        }

        public ActionResult AdminUserEditView()
        {
            //这里只有2种情况，要么是新增，要么是编辑
            string option = Request.QueryString["option"].ToString();
            if (option == "add")
            {
                ViewBag.UserName = "";
                ViewBag.Department = "";
                ViewBag.Tel = "";
                ViewBag.UserID = "";
                return View("AdminUserEditView");

            }
            else 
            {
                string UserID = Request.QueryString["UserID"].ToString();
                string sql = "select * from t_d_user where UserID=" + UserID;
                List<Dictionary<string, object>> UserInfo = new List<Dictionary<string, object>>();
                UserInfo = dao.GetList(sql, new string[] { "UserName", "Department", "Tel" });

                ViewBag.UserName = UserInfo[0]["UserName"].ToString();
                ViewBag.Department = UserInfo[0]["Department"].ToString();
                ViewBag.Tel = UserInfo[0]["Tel"].ToString();
                ViewBag.UserID = UserID;
                return View("AdminUserEditView");
            }


            
        }


        [HttpPost]
        public ActionResult UserTableRequest()
        {

            int page = Int32.Parse(Request.Form["page"]);
            int limit = Int32.Parse(Request.Form["limit"]);
            string condition = Request.Form["condition"].ToString();
            string SortName = Request.Form["SortName"].ToString();
            string Order = Request.Form["Order"].ToString();


            try
            {
                //以下是分页查询语句
                string sql = "", SqlNum = "";
                sql = " select top " + limit.ToString() + " * from " +
                        " ( " +
                        " SELECT ROW_NUMBER() OVER (order by " + SortName + " " + Order + ") as rowNumber,UserId,UserName,UserRight,Department,Tel" +
                        "" +
                        " FROM t_d_user " +
                        " where 1=1 " + condition +
                        " ) as s " +
                        " where rowNumber>" + (limit * (page - 1)).ToString();

                List<Dictionary<string, object>> list = new List<Dictionary<string, object>>();
                list = dao.GetList(sql, new string[] { "UserId", "UserName", "UserRight", "Department", "Tel" });
                SqlNum = "select count(UserId) as TotalNum FROM t_d_user where 1=1 " + condition;
                List<Dictionary<string, object>> ListNum = new List<Dictionary<string, object>>();
                ListNum = dao.GetList(SqlNum, new string[] { "TotalNum" });

                TableData td = new TableData();
                td.code = "";
                td.msg = "";
                td.count = int.Parse(ListNum[0]["TotalNum"].ToString());
                td.data = list;
                return Json(td);
            }
            catch (Exception ex)
            {
                Dictionary<string, object> datalog = new Dictionary<string, object>();
                datalog.Add("type", int.Parse("1"));
                datalog.Add("OpTime", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
                datalog.Add("OpID", int.Parse("1"));
                datalog.Add("OpLog", "异常：加载需求管理表格异常 /UserController/UserTableRequest:" + ex.Message.ToString().Replace("'", ""));
                dao.save("T_LOG", datalog);
                return Json('0');
            }

        }

        [HttpPost]
        public ActionResult AdminAddUser()
        {
            var sr = new StreamReader(Request.InputStream);
            var stream = sr.ReadToEnd();
            JObject obj = JObject.Parse(stream);
            sr.Close();
            Dictionary<string, object> result = new Dictionary<string, object>();

            string UserName= obj["UserName"] == null ? null : obj["UserName"].ToString().Replace(" ", "");
            string UserPassWord = "123456";
            string Department = obj["Department"] == null ? null : obj["Department"].ToString().Replace(" ", "");
            string Tel = obj["Tel"] == null ? null : obj["Tel"].ToString().Replace(" ", "");

            try
            {
                Dictionary<string, object> map = new Dictionary<string, object>()
                {
                    ["UserName"] = UserName,
                    ["UserPassWord"] = UserPassWord,
                    ["Department"] = Department,
                    ["Tel"] = Tel,
                    ["IsDelete"] = 0,
                };
                dao.save("t_d_user", map);
                result.Add("result", "OK");
                return Json(result);
            }
            catch (Exception e)
            {
                Console.Write(e.Message.ToString());
                result.Add("result", "error:" + e.Message.ToString().Replace("'", ""));
                return Json(result);
            }
        }

        [HttpPost]
        public ActionResult AdminUpdateUser()
        {
            var sr = new StreamReader(Request.InputStream);
            var stream = sr.ReadToEnd();
            JObject obj = JObject.Parse(stream);
            sr.Close();
            Dictionary<string, object> result = new Dictionary<string, object>();

            string UserID = obj["UserID"] == null ? null : obj["UserID"].ToString().Replace(" ", "");
            string UserName = obj["UserName"] == null ? null : obj["UserName"].ToString().Replace(" ", "");
            string Department = obj["Department"] == null ? null : obj["Department"].ToString().Replace(" ", "");
            string Tel = obj["Tel"] == null ? null : obj["Tel"].ToString().Replace(" ", "");

            try
            {
                Dictionary<string, object> map = new Dictionary<string, object>()
                {
                    ["UserName"] = UserName,
                    ["Department"] = Department,
                    ["Tel"] = Tel,
                };
                dao.update("t_d_user", map,"UserID="+UserID);
                result.Add("result", "OK");
                return Json(result);
            }
            catch (Exception e)
            {
                Console.Write(e.Message.ToString());
                result.Add("result", "error:" + e.Message.ToString().Replace("'", ""));
                return Json(result);
            }
        }


        [HttpPost]
        public ActionResult RestPW()
        {
            string UserId = Request.Form["UserId"] == null ? null : Request.Form["UserId"].ToString();
            Dictionary<string, object> result = new Dictionary<string, object>();
            if (UserId == null)
            {
                result.Add("result", "error");
                return Json(result);
            }
            string sql = "update t_d_user set UserPassWord='123456' where UserId=" + UserId + "";
            try
            {
                BaseDao.execute(sql);
                result.Add("result", "OK");
                return Json(result);
            }
            catch (Exception e)
            {
                Console.Write(e.Message.ToString());
                result.Add("result", "error:" + e.Message.ToString().Replace("'", ""));
                return Json(result);
            }

        }

        public ActionResult UserEdit()
        {
            if (Request.Cookies["UserID"] == null)
            {
                return RedirectToAction("Login", "User");
            }
            ViewBag.UserID = Request.Cookies["UserID"].Value;
            return View("UserEditView");
        }


        public ActionResult SaveUser()
        {
            var sr = new StreamReader(Request.InputStream);
            var stream = sr.ReadToEnd();
            JObject obj = JObject.Parse(stream);
            sr.Close();
            Dictionary<string, object> result = new Dictionary<string, object>();

            string UserId = obj["UserID"] == null ? null : obj["UserID"].ToString().Replace(" ", "");
            string UserPassWord = obj["UserPassWord"] == null ? null : obj["UserPassWord"].ToString().Replace(" ", "");
            string NewPassWord = obj["NewPassWord"] == null ? null : obj["NewPassWord"].ToString().Replace(" ", "");
            string Tel = obj["Tel"] == null ? null : obj["Tel"].ToString().Replace(" ", "");

            try
            {
                string sql = "select * from t_d_user where UserId=" + UserId + " and UserPassWord='" + UserPassWord + "'";
                if (1 != BaseDao.execute(sql))
                {
                    result.Add("result", "原始密码错误");
                    return Json(result);
                }
                else if (NewPassWord == "")
                {
                    sql = "update t_d_user set Tel='" + Tel + "' where UserID=" + UserId;
                    BaseDao.execute(sql);
                    result.Add("result", "OK");
                    return Json(result);
                }
                else
                {
                    sql = "update t_d_user set Tel='" + Tel + "',UserPassWord='"+NewPassWord+"' where UserID=" + UserId;
                    BaseDao.execute(sql);
                    result.Add("result", "OK");
                    return Json(result);
                }


                
            }
            catch (Exception e)
            {
                Console.Write(e.Message.ToString());
                result.Add("result", "error:" + e.Message.ToString().Replace("'", ""));
                return Json(result);
            }



        }


        public ActionResult Login()
        {
            return View("loginView");
        }

        public ActionResult loginCheck()
        {
            string UserName = Request.Form["UserName"] == null ? null : Request.Form["UserName"].ToString().Replace(" ", "");
            string UserPassWord = Request.Form["UserPassWord"] == null ? null : Request.Form["UserPassWord"].ToString().Replace(" ", "");
            string Sql = "select count(UserId) as TotalNum FROM t_d_user where UserName='" + UserName + "' and UserPassWord='" + UserPassWord + "'";
            List<Dictionary<string, object>> ListNum = new List<Dictionary<string, object>>();
            ListNum = dao.GetList(Sql, new string[] { "TotalNum" });
            if (1 != int.Parse(ListNum[0]["TotalNum"].ToString()))
            {
                ViewBag.state = "LoginError";

                //删除cookies
                HttpCookie aCookie;
                string cookieName;
                int limit = Request.Cookies.Count;
                for (int i = 0; i < limit; i++)
                {
                    cookieName = Request.Cookies[i].Name;
                    aCookie = new HttpCookie(cookieName);
                    aCookie.Expires = DateTime.Now.AddDays(-1);
                    Response.Cookies.Add(aCookie);
                }
                return View("loginView");
            }
            else
            {
                Sql= "select UserID from t_d_user where UserName='" + UserName + "' and UserPassWord='" + UserPassWord + "'";
                List<Dictionary<string, object>> UserList = new List<Dictionary<string, object>>();
                UserList = dao.GetList(Sql, new string[] { "UserID" });
                Response.Cookies["UserID"].Value = UserList[0]["UserID"].ToString();
                Response.Cookies["UserID"].Expires = DateTime.Now.AddMonths(1);
                return RedirectToAction("Index", "Home");
            }            
        }

        public ActionResult LoginOut()
        {
            //删除cookies
            HttpCookie aCookie;
            string cookieName;
            int limit = Request.Cookies.Count;
            for (int i = 0; i < limit; i++)
            {
                cookieName = Request.Cookies[i].Name;
                aCookie = new HttpCookie(cookieName);
                aCookie.Expires = DateTime.Now.AddDays(-1);
                Response.Cookies.Add(aCookie);
            }
            return View("loginView");
        }




    }
}